package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.service.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApArticleSearchService;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApArticleSearchServiceImpl implements ApArticleSearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    ApUserSearchService apUserSearchService;

    /**
     * ES文章分页搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //*****记录搜索关键字(线程池异步)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null && user.getId() != null) {
            log.info("******开始异步保存搜索关键字******");
            apUserSearchService.insert(dto.getSearchWords(), user.getId());
        }

        //设置查询条件
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键词查询
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", dto.getSearchWords()));
        //小于mindate的数据
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        //发布时间降序
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        //分页
        searchSourceBuilder.from(0).size(dto.getPageSize());
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title").preTags("<font style='color: red; font-size: inherit;'>").postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);
        //执行查询
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            //解析结果
            SearchHit[] searchHits = searchResponse.getHits().getHits();
            List<Map> result = new ArrayList<>();
            for (SearchHit searchHit : searchHits) {
                Map<String, Object> map = searchHit.getSourceAsMap();
                //得到高亮
                HighlightField highlightField = searchHit.getHighlightFields().get("title");
                if (highlightField != null && highlightField.getFragments().length > 0) {
                    Text[] fragments = highlightField.getFragments();
                    String title = StringUtils.join(fragments);
                    map.put("h_title", title);
                } else {
                    map.put("h_title", map.get("title"));
                }
                result.add(map);
            }
            return ResponseResult.okResult(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }
}
